function getRooms() {
	$.get("GetRooms",
		facebookURL({
			type: "getCurrentRooms"
		}),		
		function(data) {
			var currentlySelected = $("#rooms > tr.selected");
			if (currentlySelected.size() > 0) {
				currentlySelected = currentlySelected[0].id;
			}
			
			$("#rooms").html("");
			$("#currentRoom").html("");
			$(data).find("room").each(function() {
				$("#rooms").append(
					"<tr class='roomItem' id='list" + $(this).find("roomID").text()+ "'><td class='listRoomName'>" +
					$(this).find("roomName").text() + "</td><td>" +
						 + $(this).find("roomSize").text() +
						"</td><td>" + $(this).find("counter").text() + "</td></tr>"
				);
				
				var playersList = "";
				$(this).find("profile").each(function() {
					playersList += "<tr><td>" + 
					$(this).find("firstName").text() + " " + $(this).find('lastName').text() + 
					"</td><td>" + $(this).find("rating").text() + "</td></tr>";
				});
				
				$("#currentRoom").append(
					"<div class='room hidden' id='room" + $(this).find("roomID").text()
						+ "'><table><tbody><tr><th>Username</th><th>Rating</th></tr>"
						+ playersList + "</tbody></table></div>"
				);
			});
			
			$("#rooms > tr").click(function() {
				try {
					niftyplayer('soundPlayer').loadAndPlay('mp3/click.mp3');
				} catch(err) {}
				$("#rooms > tr").removeClass("selected");
				$(this).addClass("selected");
				$(".room").addClass("hidden");
				var currentRoomId = this.id.substring(4);
				$("#room" + currentRoomId).removeClass("hidden");
			});

			if (typeof currentlySelected == "string") {
				$("#" + currentlySelected).addClass("selected");
				$("#room" +  currentlySelected.substring(4)).removeClass("hidden");
			}
			
		});
}

function joinRoom() {
	var currentlySelected = $("#rooms > tr.selected");
	if (currentlySelected.size() > 0) {
		currentlySelected = currentlySelected[0].id;
	} else {
		jAlert("Please select a room or create one", "Info");
		return;
	}
	
	var roomID = currentlySelected.substring(4);
	
	$.post("GetRooms",
		facebookURL({
			type: "joinRoom",
			roomID: currentlySelected.substring(4)
		}), 
		function(data) {
			var status = $(data).find("status").text();
			if (status == "joined") {
				window.location.href = "http://delta-tomcat-vm.cs.tau.ac.il:40767//game.html";
			} else if ( status == "already-connected") {
				jAlert("You are already connected to this room!", "Info");
			} else {
				jAlert("We are having some problems, please try again later", "Info");
			}
		}
	);
}

function getUserDetails() {
	$.get("GetUser",
			facebookURL({
				type : "getUserDetails"
			}),
		function(data) {
			$("#userRank").text($(data).find("rating").text());
			
			var historyEntries = $(data).find('historyEntry');
			historyEntries.each(function() {
				var scoreChange = $(this).find('score').text();
				var entryDate = $(this).find('date').text();
				var rivals = $(this).find('rivals').find('string');
				var rivalsString = "";
				rivals.each(function() {
					rivalsString += $(this).text() + ", ";
				});
				rivalsString = rivalsString.substring(0, rivalsString.length-2);
				
				var newRow = "<tr><td>" + rivalsString + "</td><td>" +
					scoreChange + "</td><td>" + entryDate + "</td></tr>";
				
				$("#gameHistoryTableBody").append(newRow);
				
			});
		}
	);
}

function getHallOfFame() {
	$.get("GetRooms",
		facebookURL({
			type : "getHallOfFame"
		}),
		function(data) {
			$("#hallOfFameTableBody").html("");
			var counter = 1;
			$(data).find('entry').each(function() {
				var cash = $(this).find('int').text();

				$(this).find('Profile').each(function() {
					var username = $(this).find('firstName').text() + " " + 
					$(this).find('lastName').text();
					var userID = $(this).find('userID').text();

					var profilePicURL = "http://graph.facebook.com/" + userID +"/picture";
					var img = new Image();
					$(img).attr('src', profilePicURL);
					
					var currentRow = "<tr><td>" + counter + "</td><td>" + 
						"<span class='profilePic' id='pic" + counter + "'></span> " +
						username + "</td><td>" + cash + "</td></tr>";
					$("#hallOfFameTableBody").append(currentRow);
					$('#pic' + counter).append(img);
					counter += 1;
				});
			});
		}
	);
}

function getGameLog() {
	$.get("GetGame",
		facebookURL({
			type: "getGameLog"
		}),
		function(data) {
			var logMessage = $(data).find("entry").text();
			var logMessageTime = $(data).find("time").text();
			
			var previousMessageTime = $("#playerLog").data('previousPublicMessageTime');
			
			if (previousMessageTime == logMessageTime) {
				return;
			} else {
				$("#playerLog").data('previousPublicMessageTime', logMessageTime);
			}

			var messages = logMessage.split('^');
			
			for (var i=0; i<messages.length; i++) {
				var current = $.trim(messages[i]);
				if (current.length == 0) {
					continue;
				}
				
				$("#playerLog").append(
					"<p>&gt; " + current + "</p>"
				);
				$("#playerLog").children().last().addClass("logEntry");
			}
			
			scrollLog();
		}
	);
}

function getPrivateGameLog() {
	$.get("GetGame",
		facebookURL({
			type: "getPrivateGameLog"
		}),
		function(data) {
			var recipient = $(data).find("userID").text();
						
			if (recipient != $.cookie('userID')) {
				return;
			}
			
			var logMessage = $(data).find("entry").text();
			var logMessageTime = $(data).find("time").text();
			var previousMessageTime = $("#playerLog").data('previousPrivateMessageTime');
			
			if (previousMessageTime == logMessageTime) {
				return;
			} else {
				$("#playerLog").data('previousPrivateMessageTime', logMessageTime);
			}

			var messages = logMessage.split('^');
			
			for (var i=0; i<messages.length; i++) {
				var current = $.trim(messages[i]);
				if (current.length == 0) {
					continue;
				}
				
				$("#playerLog").append(
					"<p>&gt; " + current + "</p>"
				);
				var currentEntry = $("#playerLog").children().last();
				currentEntry.addClass("logEntry");
				currentEntry.addClass("privateMessage");
			}
			scrollLog();
		}
	);
}

function getChatMessages() {
	$.get("GetGame",
		facebookURL({
			type: "getChatMessages",
			playerIndex: $.cookie('playerIndex')
		}),
		function(data) {
			var chatMessages = $(data).text();
			if (chatMessages == "" || chatMessages == "bad-roomID" ) {
				return;
			} 

			var messages = chatMessages.split('^');
			
			for (var i=0; i<messages.length; i++) {
				var current = unescape($.trim(messages[i]));
				if (current.length == 0) {
					continue;
				}
				
				$("#playerLog").append(
					"<p>" + current + "</p>"
				);
				var currentEntry = $("#playerLog").children().last();
				currentEntry.addClass("logEntry");
				currentEntry.addClass("chatMessage");
			}
			
			scrollLog();
		}
	);
}

function getGameData() {
	$.get("GetGame",
		facebookURL({ type: "getGameData" }),
		function(data) {
			updateGameData(data);
		}
	);
}
	
function getActionCounter() {
	$.get("GetGame",
		facebookURL({ type: "getActionCounter" }),
		function(actionCounter) {
			var currentActionCounter = parseInt($(actionCounter).find('status').text());
			if ($("#dataHolder").data('actionCounter') == currentActionCounter) {
			} else {
				$("#dataHolder").data('actionCounter', currentActionCounter);
				getGameData();
			}
		}
	);
}
